package com.le.tester.leetcode;

import com.le.tester.leetcode.common.ListNode;

import java.util.List;

/**
 * createTime：2021/12/10 11:40
 * description：两数相加
 */
public class AddTwoNumbers {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//        //1.先反转两个链表
//        ListNode curNode1 = l1;
//        ListNode curNode2 = l2;
//        //2.把反转后链表的值取出相加
//        //3.得到的值反转成链表

        ListNode result = new ListNode();
        ListNode cur = result;
        int carry = 0;
        while (l1 != null || l2 != null) {
            //1.遍历获取链表中的值；保证位数相同
            int a = l1 == null ? 0 : l1.val;
            int b = l2 == null ? 0 : l2.val;
            //2.两数相加，考虑进位
            int sum = a + b + carry;

            //3.是否进位
            carry = sum / 10;

            //4.取得余数
            sum %= 10;
            cur.next = new ListNode(sum);
            cur = cur.next;
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        //查看是否还有进位
        if (carry == 1) {
            cur.next = new ListNode(1);
        }
        return result.next;
    }
}
